#include "PluginHandler.h"
#include "pgloader.h"
#include "pgmodel.h"
#include "Sington.h"
#include <QUrl>
#include <QDebug>

void PluginHandler::addNewPlugin(const QVariant &qurl)
{
    QUrl url(qurl.toString());
    qDebug() << url.fileName();

    PGLoader* loader = PGLoader::instance();
    loader->addExtensionDll(url);
}

void PluginHandler::loadPage(const int btnIndex)
{
    PGLoader* loader = PGLoader::instance();
    DllItem* item = loader->getItem(btnIndex);
    if (item) {
        PGModel* pgModel = PGModel::instance();
        if (m_btn2Header.contains(btnIndex)) {
            // 已经加载过了，直接跳转
            changeHeader(m_btn2Header[btnIndex]);
            return;
        }
        qDebug() << "Load Page" << item->m_info->m_name;
        PGModelData* data = new PGModelData;
        data->m_name = item->m_info->m_name;
        data->m_page = item->m_info->m_subWin;
        // 映射按钮和导航条
        m_btn2Header[btnIndex] = pgModel->itemCount();
        m_header2Btn[pgModel->itemCount()] = btnIndex;
        pgModel->append(data);
        // 第一个页面是首页
        // 所以当前页面应该是index+1个页面
        changeHeader(m_btn2Header[btnIndex]);
    }
}

void PluginHandler::releasePage(const int headerIndex)
{
    if (m_header2Btn.contains(headerIndex))
    {
        PGModel* pgModel = PGModel::instance();
        auto ith = m_header2Btn.find(headerIndex);
        auto itb = m_btn2Header.find(ith.value());
        qDebug() << "Remove header" << headerIndex;
        pgModel->remove(headerIndex);
        m_header2Btn.erase(ith);
        m_btn2Header.erase(itb);
        // 重置映射关系
        auto t_header2Btn = m_header2Btn;
        auto t_btn2Header = m_btn2Header;
        for (int i = headerIndex; i <= m_header2Btn.size() + 1; ++i) {
            if (m_header2Btn.contains(i)) {
                auto ditb = m_header2Btn.find(i).value();   // 获取btn位置
                auto dith = i;                              // 获取header位置
                t_header2Btn.erase(t_header2Btn.find(dith));
                t_btn2Header.erase(t_btn2Header.find(ditb));
                t_header2Btn[dith - 1] = ditb;
                t_btn2Header[ditb] = dith - 1;
            }
        }
        m_header2Btn = std::move(t_header2Btn);
        m_btn2Header = std::move(t_btn2Header);
    }
}

void PluginHandler::changeHeader(const int index)
{
    emit headerChanged(index);
    qDebug() << "Header changed";
}

void PluginHandler::changePage(const int index)
{
    emit pageChanged(PGModel::instance()->getItem(index)->m_page);
    qDebug() << "Page changed";
}

PluginHandler *PluginHandler::instance()
{
    return Sington<PluginHandler>::getInstance();
}

void PluginHandler::onAddPluginComplete()
{

}

PluginHandler::PluginHandler(QObject *parent) :
    QObject(parent)
{
    connect(PGLoader::instance(), &PGLoader::addDllComplete,
            this, &PluginHandler::onAddPluginComplete);
}
